//
//  EditSchNoticeViewController.swift
//  EduManage
//
//  Created by design02 on 17/1/3.
//  Copyright © 2017年 wsl. All rights reserved.
//

import UIKit

class EditSchNoticeViewController: BaseViewController, UICollectionViewDelegate,UICollectionViewDataSource,MWPhotoBrowserDelegate {
    
    var titleLabel: UILabel!
    var senderLabel: UILabel!
    var contentLabel: UILabel!
    var photoCollectionView: UICollectionView!
    var photoBgView: UIView!
    var oneImage: PicProgressView!
    
    var titleField: UITextView!
    var contentField: UITextView!
    
    var dic: JSON!
    
    let collectionIdentifier = "PicCollectionViewCellIdentifier"
    let imageArray = NSMutableArray()
    var photoArray = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "通知公告"
        
        
        InitViews()
        self.automaticallyAdjustsScrollViewInsets = false
        
        NotificationCenter.default.addObserver(self, selector: #selector(EditSchNoticeViewController.showBigImage(_:)), name: NSNotification.Name(rawValue: "showBigImage"), object: nil)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "完成", style: UIBarButtonItemStyle.plain, target: self, action: #selector(EditSchNoticeViewController.InitViews))
        
    }
    
    func InitViews() {
        
        var title = dic["title"].stringValue
        var content = dic["msg"].stringValue
        
        title = title.removingPercentEncoding!
        content = content.removingPercentEncoding!
        
        let time = dic["datetime"].stringValue
        let sender = dic["teaname"].stringValue
        let imageUrl = dic["fileurl"].stringValue
        
        titleField = UITextView.init(frame: CGRect(x: 10, y: 84, width: screenW-20, height: 40))
        titleField.backgroundColor = UIColor.clear
        titleField.layer.borderColor = barColor.cgColor
        titleField.layer.borderWidth = 1.0
        titleField.layer.cornerRadius = 3.0
        titleField.font = UIFont.systemFont(ofSize: 16)
        titleField.text = title
        titleField.isEditable = true
        
        
        senderLabel = UILabel.init(frame: CGRect(x: 10, y: titleField.frame.maxY + 5, width: screenW - 20, height: 30))
        senderLabel.font = UIFont.systemFont(ofSize: 14)
        senderLabel.textColor = textlight
        senderLabel.textAlignment = NSTextAlignment.left
        senderLabel.text = sender + " " + time.replacingOccurrences(of: "T", with: " ")
        
        
        contentField = UITextView.init(frame: CGRect(x: 10, y: senderLabel.frame.maxY + 5, width: screenW - 20, height: 100))
        contentField.text = content
        contentField.font = UIFont.systemFont(ofSize: 15)
        contentField.textColor = UIColor.darkGray
        contentField.backgroundColor = UIColor.clear
        contentField.textAlignment = NSTextAlignment.left
        
        contentField.layer.borderColor = barColor.cgColor
        contentField.layer.borderWidth = 1.0
        contentField.layer.cornerRadius = 3.0

        self.view.addSubview(titleField)
        self.view.addSubview(senderLabel)
        self.view.addSubview(contentField)
        
        if imageUrl.characters.count > 0 {
            let array = imageUrl.components(separatedBy: "|") as NSArray
            
            photoBgView = UIView.init(frame: CGRect(x: 10, y: contentLabel.frame.maxY + 5, width: screenW - 20, height: getPhotoCollectionHeight(array)))
            photoBgView.backgroundColor = UIColor.white
            self.view.addSubview(photoBgView)
            
            if array.count == 1 {
                oneImage = PicProgressView.init(frame: CGRect(x: photoBgView.frame.minX+5, y: photoBgView.frame.minY+5, width: photoBgView.frame.width-10, height: photoBgView.frame.height-10))
                oneImage.isUserInteractionEnabled = true
                let showImage = UITapGestureRecognizer.init(target: self, action: #selector(EditSchNoticeViewController.showImage))
                oneImage.addGestureRecognizer(showImage)
                self.view.addSubview(oneImage)
                let photo = imageUrl.replacingOccurrences(of: "../..", with: "")
                let imageurl = server + priImg + photo + "&width=400&mode=W"
                oneImage.imageUrl = imageurl
            }else {
                imageArray.addObjects(from: array as [AnyObject])
//                (frame: CGRect(x: 10, y: switchBT.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray)), collectionViewLayout: AddPhotoFlowLayout.init())
                photoCollectionView = UICollectionView.init(frame: CGRect(x: photoBgView.frame.minX+5, y: photoBgView.frame.minY+5, width: photoBgView.frame.width-10, height: self.photoBgView.frame.height-10), collectionViewLayout: photoFlowLayout.init())
                photoCollectionView.backgroundColor = UIColor.white
                photoCollectionView.register(PicCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
                photoCollectionView.scrollsToTop = true
                photoCollectionView.delegate = self
                photoCollectionView.dataSource = self
                self.view.addSubview(photoCollectionView)
            }
            
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PicCollectionViewCell
        cell.backgroundColor = UIColor.white
        var photo = imageArray.object(at: (indexPath as NSIndexPath).row) as! String
        photo = photo.replacingOccurrences(of: "../..", with: "")
        let imageurl = server + priImg + photo + "&width=300&mode=W"
        cell.imageUrl = imageurl
        return cell;
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let imageUrl = dic["fileurl"].stringValue
        let index = String((indexPath as NSIndexPath).row)
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showBigImage"), object: nil, userInfo: ["url" : imageUrl, "index" : index])
        
    }
    /**
     显示大图
     */
    func showImage() {
        let imageUrl = dic["fileurl"].stringValue
        let htmlurl = dic["htmlurl"].stringValue
        if htmlurl.characters.count != 0  {
            UIApplication.shared.openURL(URL.init(string: htmlurl)!)
        }else{
            let index = "0"
            NotificationCenter.default.post(name: Notification.Name(rawValue: "showBigImage"), object: nil, userInfo: ["url" : imageUrl, "index" : index])
        }
        
    }
    
    /**
     显示大图
     
     - parameter notification: <#notification description#>
     */
    func showBigImage(_ notification: Notification) {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let imageUrl = dic.object(forKey: "url") as! String
        let index = UInt(dic.object(forKey: "index") as! String)
        let array = imageUrl.components(separatedBy: "|")
        let array1 = NSMutableArray()
        array1.addObjects(from: array)
        let n = array1.count
        photoArray = NSMutableArray()
        for i in 0...n-1 {
            var url = array1.object(at: i) as! String
            url = server + url.replacingOccurrences(of: "../..", with: "")
            photoArray.add(MWPhoto.init(url: URL.init(string: url)))
            
        }
        let browser: MWPhotoBrowser = MWPhotoBrowser.init(delegate: self)
        // Set options
        browser.displayActionButton = true
        browser.displayNavArrows = false
        browser.displaySelectionButtons = false
        browser.zoomPhotosToFill = true
        browser.alwaysShowControls = false
        browser.enableGrid = true
        browser.startOnGrid = false
        browser.autoPlayOnAppear = false
       
        browser.setCurrentPhotoIndex(index!)
        self.navigationController?.pushViewController(browser, animated: true)
        browser.showNextPhoto(animated: true)
        browser.showPreviousPhoto(animated: true)
    }
    func numberOfPhotos(in photoBrowser: MWPhotoBrowser!) -> UInt {
        return UInt(photoArray.count)
    }
    func photoBrowser(_ photoBrowser: MWPhotoBrowser!, photoAt index: UInt) -> MWPhotoProtocol! {
        
        if index < UInt(photoArray.count) {
            
            return photoArray.object(at: Int(index)) as! MWPhotoProtocol
            
        }
        
        return nil;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
